import dotenv from 'dotenv';
import path from 'path';
import fs from 'fs'

// 先构造出.env*文件的绝对路径
const appDirectory = fs.realpathSync(process.cwd());
const resolveApp = ( relativePath ) => path.resolve(appDirectory, 'env', relativePath);
const pathsDotenv = resolveApp(".env");
const curmode = currentModel()

// 按优先级由高到低的顺序加载.env文件
if( fs.existsSync(`${pathsDotenv}.local`)) dotenv.config({ path: `${pathsDotenv}.local` });
if( fs.existsSync(`${pathsDotenv}.${curmode}`)) dotenv.config({ path: `${pathsDotenv}.${curmode}` });

function currentModel(){
    const argvs = process.argv || []
    let find = -1
    const cur = 'development'
    for(let index=0; index<argvs.length; index++){
        if(find>=0) { 
            process.env.MODE = argvs[index]
            return argvs[index]
        }
        if( argvs[index] === '--mode'){
            find = index
        }
    }
    process.env.MODE = cur
    return cur;
}